// src/utils/request.ts
import axios, { type AxiosInstance, type AxiosRequestConfig } from 'axios';
import { ElLoading } from 'element-plus';

// 扩展配置接口
export interface CustomRequestConfig extends AxiosRequestConfig {
    showLoading?: boolean;
    ignoreError?: boolean;
    retry?: boolean;
    retryCount?: number;
    retryDelay?: number;
}

let loadingInstance: ReturnType<typeof ElLoading.service>;
let loadingCount = 0;

const service: AxiosInstance = axios.create({
    baseURL: import.meta.env.VITE_API_BASE_URL,
    timeout: 10000,
    headers: { 'Content-Type': 'application/json' }
});

// 显示 loading
function showLoading() {
    if (loadingCount === 0) {
        loadingInstance = ElLoading.service({
            lock: true,
            text: '加载中...',
            background: 'rgba(0, 0, 0, 0.7)'
        });
    }
    loadingCount++;
}

// 隐藏 loading
function hideLoading() {
    loadingCount--;
    if (loadingCount <= 0) {
        loadingInstance?.close();
        loadingCount = 0;
    }
}

// 请求拦截器
service.interceptors.request.use(config => {
    const customConfig = config as CustomRequestConfig;

    // 根据配置决定是否显示loading
    if (customConfig.showLoading !== false) {
        showLoading();
    }

    const token = localStorage.getItem('token');
    if (token) {
        config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
});

// 响应拦截器
service.interceptors.response.use(
    response => {
        const customConfig = response.config as CustomRequestConfig;

        // 根据配置决定是否隐藏loading
        if (customConfig.showLoading !== false) {
            hideLoading();
        }

        const res = response.data;

        // 根据业务逻辑判断请求是否成功
        if (response.status === 200 && (res.success === true || res.code === 200)) {
            return res;
        }

        // 如果配置了忽略错误，直接返回原始响应
        if (customConfig.ignoreError) {
            return res;
        }

        const errorMsg = res.message || '请求失败';
        return Promise.reject(new Error(errorMsg));
    },
    error => {
        const customConfig = error.config as CustomRequestConfig;

        // 根据配置决定是否隐藏loading
        if (customConfig?.showLoading !== false) {
            hideLoading();
        }

        // 重试逻辑
        if (customConfig?.retry && customConfig.retryCount && customConfig.retryCount > 0) {
            const retryCount = customConfig.retryCount - 1;
            const retryDelay = customConfig.retryDelay || 1000;

            return new Promise(resolve => {
                setTimeout(() => {
                    const retryConfig = {
                        ...customConfig,
                        retryCount
                    };
                    resolve(service(retryConfig));
                }, retryDelay);
            });
        }

        // 错误处理
        if (error.response) {
            switch (error.response.status) {
                case 401:
                    localStorage.removeItem('token');
                    window.location.href = '/login';
                    break;
                case 500:
                    console.error('[API] 服务器错误:', error.config?.url);
                    break;
            }
        }

        // 如果配置了忽略错误，直接返回错误响应
        if (customConfig?.ignoreError) {
            return error.response?.data || error;
        }

        return Promise.reject(error);
    }
);

// 修改请求函数以支持 CustomRequestConfig
const request = <T = any>(config: CustomRequestConfig): Promise<T> => {
    return service(config);
};

const get = <T = any>(url: string, params?: object, config?: CustomRequestConfig): Promise<T> =>
    request({ url, method: 'GET', params, ...config });

const post = <T = any>(url: string, data?: object, config?: CustomRequestConfig): Promise<T> =>
    request({ url, method: 'POST', data, ...config });

export { request, get, post };
export default service;
